import { useRef, useState, useEffect } from 'react';
import { ReloadOutlined, SettingOutlined } from '@ant-design/icons';
import type { ActionType } from '@ant-design/pro-components';
import {
  operationAlarmListApi,
  operationAlarmHandleApi,
  operationAlarmDetailApi,
  operationAlarmStatisticsApi,
} from '@/api/operationAlarmApi';
import type { AlarmRecord, AlarmItem, AlarmRecordStatistics } from '@/api/operationAlarmApi';
import { TableLocalePresets } from '@/utils/tableUtils';
import { EnableStatusType, getEnumItem, typeToValueEnum, AlarmLevelEnum } from '@/constants';

const AlarmWarningList = () => {
  const actionRef = useRef<ActionType>(null);
  const [loading, setLoading] = useState(false);
  const [detailData, setDetailData] = useState<AlarmItem | null>(null);
  const [handleForm] = AForm.useForm();
  const [statistics, setStatistics] = useState<AlarmRecordStatistics | null>(null);
  // 抽屉状态
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [drawerType, setDrawerType] = useState<'detail' | 'handle'>('detail'); // 抽屉类型：详情/处理

  useEffect(() => {
    const fetchStatistics = async () => {
      try {
        // 使用真实API
        const res = await operationAlarmStatisticsApi();
        if (res.success) {
          setStatistics(res.data);
        } else {
          window.$message.error(res.message || '获取告警统计数据失败');
        }
      } catch (error) {
        console.error('获取告警统计数据失败:', error);
        window.$message.error('获取告警统计数据失败');
      }
    };
    fetchStatistics();
  }, []);

  // 获取告警列表
  const fetchAlarmList = async (params: any) => {
    setLoading(true);
    try {
      // 使用真实API
      const res = await operationAlarmListApi({
        pageNum: params.current,
        pageSize: params.pageSize,
        ...params,
      });

      if (res.success) {
        return {
          success: true,
          data: res.data?.records || [],
          total: res.data?.total || 0,
        };
      } else {
        window.$message.error(res.message || '获取告警列表失败');
        return {
          success: false,
          data: [],
          total: 0,
        };
      }
    } catch (error) {
      console.error('获取告警列表失败:', error);
      window.$message.error('获取告警列表失败');
      return {
        success: false,
        data: [],
        total: 0,
      };
    } finally {
      setLoading(false);
    }
  };

  // 处理告警 - 使用您选择的方法
  const handleAlarmSubmit = async () => {
    try {
      const values = await handleForm.validateFields();

      if (!detailData?.id) return;

      // 使用真实API
      const res = await operationAlarmHandleApi({
        id: detailData.id,
        handleResult: values.handleResult,
      });

      if (res.success) {
        window.$message.success('处理成功');
        setDrawerVisible(false);
        handleForm.resetFields();
        setDetailData(null);
        actionRef.current?.reload();
      } else {
        window.$message.error(res.message || '处理失败');
      }
    } catch (error) {
      console.error('处理告警失败:', error);
      window.$message.error('处理告警失败');
    }
  };

  // 处理告警
  const handleAlarm = async (values: { handleResult: string }) => {
    if (!detailData?.id) return;

    try {
      // 使用真实API
      const res = await operationAlarmHandleApi({
        id: detailData.id,
        handleResult: values.handleResult,
      });

      if (res.success) {
        window.$message.success('处理成功');
        setDrawerVisible(false);
        handleForm.resetFields();
        setDetailData(null);
        actionRef.current?.reload();
      } else {
        window.$message.error(res.message || '处理失败');
      }
    } catch (error) {
      console.error('处理告警失败:', error);
      window.$message.error('处理告警失败');
    }
  };

  // 获取告警详情
  const fetchAlarmDetail = async (record: AlarmRecord) => {
    if (!record.id) return;

    try {
      // 使用真实API
      const res = await operationAlarmDetailApi({ id: record.id });
      if (res.success) {
        setDetailData(res.data);
        setDrawerType('detail');
        setDrawerVisible(true);
      } else {
        window.$message.error(res.message || '获取告警详情失败');
        return;
      }
    } catch (error) {
      console.error('获取告警详情失败:', error);
      window.$message.error('获取告警详情失败');
    }
  };

  // 显示处理抽屉
  const showHandleDrawer = (record: AlarmRecord) => {
    // 先获取详情数据，再显示处理抽屉
    if (!record.id) return;

    // 使用真实API获取详情
    operationAlarmDetailApi({ id: record.id })
      .then(res => {
        if (res.success) {
          setDetailData(res.data);
          setDrawerType('handle');
          setDrawerVisible(true);
        } else {
          window.$message.error(res.message || '获取告警详情失败');
        }
      })
      .catch(error => {
        console.error('获取告警详情失败:', error);
        window.$message.error('获取告警详情失败');
      });
  };

  // 显示详情抽屉
  const showDetailDrawer = (record: AlarmRecord) => {
    fetchAlarmDetail(record);
  };

  const columns = [
    {
      title: '告警ID',
      dataIndex: 'id',
      key: 'id',
      width: 100,
      search: false,
    },
    {
      title: '告警规则名称',
      dataIndex: 'ruleName',
      key: 'ruleName',
      width: 160,
      search: true,
    },
    {
      title: '告警规则描述',
      dataIndex: 'ruleRemark',
      key: 'ruleRemark',
      width: 180,
      search: false,
      ellipsis: true,
    },
    {
      title: '告警等级',
      dataIndex: 'level',
      key: 'level',
      width: 100,
      search: true,
      valueEnum: typeToValueEnum(AlarmLevelEnum),
      render: (_: any, record: AlarmRecord) => {
        const level = getEnumItem(AlarmLevelEnum, record.level);
        return <ABadge status={level?.status as any} text={level?.label || '未知'} />;
      },
    },
    {
      title: '触发时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      search: false,
    },
    {
      title: '处理时间',
      dataIndex: 'alarmHandleTime',
      key: 'alarmHandleTime',
      width: 180,
      search: false,
    },
    {
      title: '告警状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      search: true,
      valueEnum: {
        0: { text: '未处理', status: 'Error' },
        1: { text: '已处理', status: 'Success' },
      },
      render: (_: any, record: AlarmRecord) => {
        const status =
          record.status === 0
            ? { label: '未处理', status: 'error', color: 'red' }
            : { label: '已处理', status: 'success', color: 'green' };
        return <ABadge status={status.status as any} text={status.label} />;
      },
    },
    {
      title: '处理结果',
      dataIndex: 'handleResult',
      key: 'handleResult',
      width: 150,
      search: false,
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      search: false,
      render: (_: any, record: AlarmRecord) => (
        <ASpace size="small">
          <AButton type="link" size="small" onClick={() => showDetailDrawer(record)}>
            详情
          </AButton>
          {record.status === 0 && (
            <AButton type="link" size="small" onClick={() => showHandleDrawer(record)}>
              处理
            </AButton>
          )}
        </ASpace>
      ),
    },
  ];

  return (
    <div className="w-full">
      {statistics && (
        <ACard className="mb-4">
          <div className="grid grid-cols-5 gap-4">
            <div className="bg-gray-50 p-4 rounded-md">
              <AStatistic title="未处理告警数" value={statistics.noHandleCount || 0} />
            </div>
            <div className="bg-gray-50 p-4 rounded-md">
              <AStatistic title="告警总数" value={statistics.alarmCount || 0} />
            </div>
            <div className="bg-gray-50 p-4 rounded-md">
              <AStatistic
                title="紧急"
                value={statistics.urgentCount || 0}
                valueStyle={{ color: '#ff4d4f' }}
              />
            </div>
            <div className="bg-gray-50 p-4 rounded-md">
              <AStatistic
                title="重要"
                value={statistics.importantCount || 0}
                valueStyle={{ color: '#faad14' }}
              />
            </div>
            <div className="bg-gray-50 p-4 rounded-md">
              <AStatistic title="普通" value={statistics.ordinaryCount || 0} />
            </div>
          </div>
        </ACard>
      )}
      <PProTable<AlarmRecord>
        className="mh-table"
        actionRef={actionRef}
        columns={columns}
        request={fetchAlarmList}
        rowKey="id"
        search={{
          span: 6,
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`,
        }}
        scroll={{ x: 1000 }}
        size="small"
        options={{
          density: false,
          reloadIcon: (
            <AButton icon={<ReloadOutlined />} key="reload">
              刷新
            </AButton>
          ),
          setting: {
            draggable: true,
            checkable: true,
            showListItemOption: true,
            settingIcon: <AButton icon={<SettingOutlined />}>设置</AButton>,
            listsHeight: 400,
          },
        }}
        locale={TableLocalePresets.product(actionRef)}
      />

      {/* 告警详情和处理抽屉 */}
      <ADrawer
        title={drawerType === 'detail' ? '告警详情' : '处理告警'}
        width={800}
        open={drawerVisible}
        onClose={() => {
          setDrawerVisible(false);
          setDetailData(null);
          handleForm.resetFields();
        }}
        footer={
          <div className="flex justify-end">
            <AButton
              onClick={() => {
                setDrawerVisible(false);
                setDetailData(null);
                handleForm.resetFields();
              }}
              className="mr-2"
            >
              返回
            </AButton>
            {drawerType === 'handle' && (
              <AButton type="primary" onClick={handleAlarmSubmit}>
                提交
              </AButton>
            )}
          </div>
        }
      >
        {detailData && (
          <div>
            {/* 详情信息展示 */}
            <ACard title="告警详情信息" size="small" className="mb-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p>
                    <strong>告警规则名称:</strong> {detailData.ruleName}
                  </p>
                  <p>
                    <strong>告警级别:</strong>{' '}
                    <ABadge
                      status={
                        (getEnumItem(AlarmLevelEnum, detailData.level)?.status as any) || 'default'
                      }
                      text={getEnumItem(AlarmLevelEnum, detailData.level)?.label || '未知'}
                    />
                  </p>
                  <p>
                    <strong>告警状态:</strong>{' '}
                    <ABadge
                      status={detailData.status === 0 ? 'error' : 'success'}
                      text={detailData.status === 0 ? '未处理' : '已处理'}
                    />
                  </p>
                  <p>
                    <strong>告警设备:</strong> {detailData.alramDevices}
                  </p>
                </div>
                <div>
                  <p>
                    <strong>告警触发时间:</strong> {detailData.createTime}
                  </p>
                  <p>
                    <strong>告警处理时间:</strong> {detailData.alarmHandleTime}
                  </p>
                  <p>
                    <strong>创建人:</strong> {detailData.createBy}
                  </p>
                </div>
              </div>
              <div className="mt-4">
                <p>
                  <strong>规则描述:</strong> {detailData.ruleRemark}
                </p>
              </div>
              <div className="mt-4">
                <p>
                  <strong>告警源数据:</strong>
                </p>
                <pre className="bg-gray-100 p-2 rounded whitespace-normal">
                  {detailData.sourceData || '无'}
                </pre>
              </div>
              {detailData.handleResult && (
                <div className="mt-4">
                  <p>
                    <strong>处理结果:</strong>
                  </p>
                  <p className="bg-gray-100 p-2 rounded">{detailData.handleResult}</p>
                </div>
              )}
            </ACard>

            {/* 处理表单（仅在处理模式下显示） */}
            {drawerType === 'handle' && (
              <ACard title="处理信息" size="small">
                <AForm
                  form={handleForm}
                  onFinish={handleAlarm}
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 16 }}
                >
                  <AForm.Item
                    label="处理结果"
                    name="handleResult"
                    rules={[{ required: true, message: '请输入处理结果!' }]}
                  >
                    <AInput.TextArea rows={4} placeholder="请输入处理结果" />
                  </AForm.Item>
                </AForm>
              </ACard>
            )}
          </div>
        )}
      </ADrawer>
    </div>
  );
};

export default AlarmWarningList;
